import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class WordCount
{
    private Map<String, Integer> count = new HashMap<>();

    public void countWord(String[] words)
    {
        for (int i = 0; i < words.length; i++)
        {
            if (count.containsKey(words[i]))
            {
                count.put(words[i], count.get(words[i]) + 1);
            }
            else
            {
                count.put(words[i], 1);
            }
        }
    }

    private List<CountableWord> sort() //按照计数降序，单词升序
    {
        String words[] = count.keySet().toArray(new String[0]);
        Integer counts[] = count.values().toArray(new Integer[0]);
        List<CountableWord> cwords = new ArrayList<>();
        for (int i = 0; i < words.length; i++)
        {
            cwords.add(new CountableWord(words[i], counts[i]));
        }
        cwords.sort(CountableWord::compareTo);
        return cwords;
    }

    @Override
    public String toString()
    {
        List <CountableWord> cwords = sort();
        String result = "";
        for (int i = 0; i < cwords.size(); i++)
        {
            result += cwords.get(i).getWord() + " " + cwords.get(i).getCount() + "\r\n";
        }
        return result;
    }

    public void output(File text) //将output.txt输出到输入的文件的相同目录
    {
        File output = new File(new File(text.getAbsolutePath()).getParent() + "\\output.txt");
        boolean flag = false;
        if (!output.exists())
        {
            try
            {
                flag = output.createNewFile();
            }
            catch (IOException e)
            {
                System.err.println("文件创建失败");
                System.exit(1);
            }
        }
        if (!flag)
        {
            System.err.println("文件创建失败：文件已存在");
            System.exit(1);
        }
        OutputStream os = null;
        try
        {
            os = new FileOutputStream(output);
        }
        catch (FileNotFoundException e)
        {
            System.err.println("找不到指定的文件");
            System.exit(1);
        }
        String result = toString();
        byte[] bytes = result.getBytes(StandardCharsets.UTF_8);
        try
        {
            os.write(bytes);
            os.flush();
            os.close();
        }
        catch (IOException e)
        {
            System.err.println("文件写入失败");
            System.exit(1);
        }
    }

    public static void main(String[] args)
    {
        WordCount wordCount = new WordCount();
        File text = new File(args[0]);
        if (text.exists() && (!text.canRead()))
        {
            System.err.println("无法读取文件");
            System.exit(1);
        }
        Scanner input = null;
        try{
            input = new Scanner(text);
        }
        catch (FileNotFoundException e)
        {
            System.err.println("文件不存在");
            System.exit(1);
        }
        while (input.hasNextLine())
        {
            String line = input.nextLine();
            String words[] = line.split("\\s+");
            wordCount.countWord(words);
        }
        wordCount.output(text);
    }
}
